<!DOCTYPE html>
<html>
<head>
    <title>生成综合订单</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</head>
<body style="background-color:#fffbf6">
    {% include 'top_bar.html' %}
    <div id="container">
        <div id="compPicBox">
            <h3>上传快团团导出的文件</h3>
            <div style="color:#f1a63c;font-size: 12px;">文件名命名示例：<b>20250110-综合-导出订单-01.xlsx</b></div>
            <input type="file" name='kttXlsx' id="fileInput" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="display: none;">
            <div id="uploadXls" ></div>
            <div id="uploadMsg"></div>
            <div id="dealMsg"></div>
            <button id='browseButton' onclick="openFileBrowser();" style="margin-top:20px;">浏览</button>
            <button id="upload" onclick="uploadFile();">上传</button>
            <button id="deal" onclick="deal();">处理</button>
            <div id="dl" style="margin-top:10px;display:none;">
                <a id="downloadLink" href="#" onclick="generateDownloadLink()">下载文件</a>
            </div>
            <div id="orderMsg" style="margin-top:20px;"></div>
        </div>
    </div>

    
    <script src="../static/js/common.js"></script>
    <script>
        let selectedFile;

        document.addEventListener("DOMContentLoaded",function(){
            document.getElementById('fileInput').addEventListener('change', handleFileSelection);
                const fileInput = document.getElementById("fileInput");
                fileInput.addEventListener("change", handleFileSelection);

        });

        function generateDownloadLink() {
            const fn = selectedFile.name; // 动态获取param1的值          

            const link = document.getElementById('downloadLink');
            link.href = '{{ url_for("zip_and_download_mix_ktt") }}' + '?fn=' + encodeURIComponent(fn);
            
            link.addEventListener('click',hideDownload);
            // hideDownload();
        }

        function hideDownload(){
            const dl=document.getElementById('dl');
            // const prompt=document.getElementById('prompt');
            // prompt.innerText='';
            // prompt.style.display='block';
            dl.style.display='none';
        }

        function deal(){
            const dl=document.getElementById('dl');
            const dealMsg=document.getElementById('dealMsg');
            const orderMsg=document.getElementById('orderMsg');
            orderMsg.innerHTML='';
            dealMsg.innerHTML=''
            dealMsg.innerHTML='正在处理'
            fetch('./deal_ktt_export',{
                    method:"POST",
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body: JSON.stringify({'fileName':selectedFile.name})
                })
                .then(response=>response.json())
                .then(data=>{
                    console.log(data)
                    if(data['res']==='ok'){                        
                        dealMsg.innerHTML='处理完成';
                        dl.style.display='block';
                        // console.log(data['data']['sum_txt'])
                        const sumTxt=data['data']['sum_txt'].replace(/\n\n/g,'<br><br>');
                        console.log(sumTxt);
                        orderMsg.innerHTML=sumTxt;
                        generateDownloadLink();
                    }else{
                        dealMsg.innerHTML=`<span style="color:red;">${data['error']}</span>`;
                    }
                })
                .catch(error=>{
                    console.error('处理数据错误：',error)
                });
        }

        function newSelectedName(name){           
            const cusName=document.getElementById('cusName').value;
            const dateSelect=dateToString(document.getElementById('date').value,'digit8');
            const fileExtension = name.split('.').pop();
            const filename = insIdPage + '-' + cusName + '-' + dateSelect + '.' + fileExtension;
  
            return filename
        }

        function handleFileSelection(event) {
            selectedFile = event.target.files[0];
            console.log(selectedFile.name)
            const uploadMsg=document.getElementById('uploadMsg');
            // const newFileName=newSelectedName(selectedFile.name);

            uploadMsg.textContent=`已选择文件：${selectedFile.name}`
         
           
        }

        function reSetupFileSelection(){
            const fileInput = document.getElementById('fileInput'); // 获取文件上传的 input 元素
            fileInput.addEventListener('change', handleFileSelection);
            document.getElementById('uploadMsg').textContent='';
        }


        function openFileBrowser() {
            const orderMsg=document.getElementById('orderMsg');
            orderMsg.innerHTML='';
            const dealMsg=document.getElementById('dealMsg');
            dealMsg.innerHTML='';
            const uploadMsg=document.getElementById('uploadMsg');
            uploadMsg.innerHTML='';
            document.getElementById('fileInput').click();
        }

        function uploadFile() {
            const orderMsg=document.getElementById('orderMsg');
            orderMsg.innerHTML='';
            if (!selectedFile) {
                alert("请选择要上传的文件");
                return;
            }

            // const newFileName=newSelectedName(selectedFile.name);
            const newFileName=selectedFile.name;
            
            const url = "/upload_file?filename=" + encodeURIComponent(newFileName);

            let formData = new FormData();
            formData.append("file", selectedFile); 
            formData.append("filename", newFileName);
            // console.log(url)

            let xhr = new XMLHttpRequest();
            xhr.open("POST", url);
            xhr.onload = function() {
                console.log('xhr status:',xhr.status)
                const errorResponse = JSON.parse(xhr.responseText);
                const errorMessage = errorResponse.message;
                // console.log('message:',errorMessage)
                if (xhr.status === 200) {
                    document.getElementById('uploadMsg').textContent=`${newFileName} 上传成功`;
                    // alert("上传成功");
                } else {
                    document.getElementById('uploadMsg').textContent='上传失败，请联系管理员。'
                    alert("上传失败，请联系管理员。错误："+errorMessage);
                }
            };
            xhr.send(formData);
        }

    
    

    </script>
</body>
</html>